package com.singfan.app.controller;

import com.singfan.app.CouponProvide;
import com.singfan.core.dao.database.model.CustomerCoupon;
import com.singfan.core.dao.database.model.Shop;
import com.singfan.core.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Author: hansonghe
 * Date: 2015-09-15 14:18
 * Desc:
 */
@Controller
public class AdminController extends SingFanControllerBase {
    @Autowired
    private IShopService shopService;
    @RequestMapping(value="/v1/admin/coupon/provide", method= RequestMethod.POST)
    public void provideCoupon(HttpServletRequest request, HttpServletResponse response){
        CouponProvide couponProvide = request2Bean(request, CouponProvide.class);
        String shopMasterName = null;
        String shopSlaveName = null;
        if (couponProvide.getShopId() > 0){
            Shop shop = shopService.findShop(couponProvide.getShopId());
            if (shop != null){
                shopMasterName = shop.getMasterShopName();
                shopSlaveName = shop.getSlaveShopName();
            }
        }

        List<Long> customerIdList = customerService.findAllCustomerIdList();
        for (Long customerId : customerIdList){
            Date now = new Date();
            CustomerCoupon customerCoupon = new CustomerCoupon();
            customerCoupon.setCustomerId(customerId);
            customerCoupon.setAmount(couponProvide.getAmount());
            customerCoupon.setPriceCondition(couponProvide.getPriceCondition());
            customerCoupon.setShopId(couponProvide.getShopId());
            customerCoupon.setShopMasterName(shopMasterName);
            customerCoupon.setShopSlaveName(shopSlaveName);
            customerCoupon.setExpiredTime(new Date(couponProvide.getExpiredTime()));
            customerCoupon.setCreateTime(now);

            customerService.createCustomerCoupon(customerCoupon);
        }

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().write("OK");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
